<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { getTopMenu, initRouter } from "@/router/utils";
import { bg } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import globalAxios from "@/utils/http/index";

// import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import { SendCodeApi } from "@/api/identity";
import { Configuration } from "@/__api__/configuration";
import {
  OrderMgmtApi,
  OrderMgmtApiFactory
} from "@/__api__/MealTicket/api/order-mgmt-api";
const { VITE_CLIENT_ID, VITE_SYSTEM_ID } = import.meta.env;

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();

const ruleForm = reactive({
  phoneNumber: "",
  verificationCode: ""
});

declare let TencentCaptcha: any;

const sendCode = async () => {
  if (!ruleForm.phoneNumber) {
    message("请输入手机号", { type: "warning" });
    return;
  }

  const captcha = new TencentCaptcha(
    "2082434476",
    res => {
      if (res.ticket) {
        SendCodeApi({
          systemId: VITE_SYSTEM_ID,
          phoneNumber: ruleForm.phoneNumber,
          captchaTicket: res.ticket,
          data: {
            CaptchaType: "9",
            Randstr: res.randstr
          },
          verificationCodeType: 1
        }).then(() => {
          message("发送验证码成功", { type: "success" });
        });
      }
    },
    {
      bizState: "data-biz-state",
      needFeedBack: false
    }
  );
  captcha.show(); // 显示验证码
};

const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      useUserStoreHook()
        .loginByUsername({
          phoneNumber: ruleForm.phoneNumber,
          verificationCode: ruleForm.verificationCode,
          systemId: VITE_SYSTEM_ID,
          clientId: VITE_CLIENT_ID
        })
        .then(() => {
          useUserStoreHook()
            .getUserInfo()
            .then(() => {
              initRouter().then(() => {
                router.push(getTopMenu(true).path);
                message("登录成功", { type: "success" });
              });
            });
        })
        .catch(() => {
          loading.value = false;
        });
    } else {
      loading.value = false;
      return fields;
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});

const getListFactory = () => {
  var _configuration = new Configuration({
    basePath:
      "https://api.hg.hygeian.com.cn:13443/institution-hgyy/api-meal-ticket",
    baseOptions: { headers: { nickName: "qingshang1111111111111111111111" } }
  });

  var req = {
    timePicker: [null, null],
    type: "",
    keyword: null,
    startDateTime: null,
    endDateTime: null,
    sorting: null,
    skipCount: 0,
    maxResultCount: 10
  };

  OrderMgmtApiFactory(_configuration, undefined, globalAxios)
    .apiOrderMgmtListPost(req)
    .then(res => {
      console.log(res);
    })
    .catch(e => {
      //异常处理
    });
};

const getListObject = () => {
  var req = {
    timePicker: [null, null],
    type: "",
    keyword: null,
    startDateTime: null,
    endDateTime: null,
    sorting: null,
    skipCount: 0,
    maxResultCount: 10
  };
  var _client = new OrderMgmtApi();
  _client
    .apiOrderMgmtListPost(req)
    .then(res => {
      const _res = res.data;
      console.log(_res);
    })
    .catch(e => {
      console.log(e);
    });
};


</script>

<template>
  <div class="select-none">
    <div class="hy_login">
      <div class="bgimg">
        <img :src="bg" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <el-button @click="getListFactory">F发送请求</el-button>
          <el-button @click="getListObject">O发送请求</el-button>

          <Motion>
            <div class="welcome">WelCome</div>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入手机号',
                    trigger: 'blur'
                  }
                ]"
                prop="phoneNumber"
              >
                <el-input
                  clearable
                  v-model="ruleForm.phoneNumber"
                  placeholder="请输入手机号"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入验证码',
                    trigger: 'blur'
                  }
                ]"
                prop="verificationCode"
              >
                <el-input
                  v-model="ruleForm.verificationCode"
                  clearable
                  placeholder="请输入验证码"
                  :prefix-icon="useRenderIcon('ri:shield-keyhole-line')"
                >
                  <template v-slot:append>
                    <el-button
                      size="default"
                      type="primary"
                      style="width: 150px"
                      @click="sendCode"
                      >发送验证码</el-button
                    >
                  </template>
                </el-input>
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-button
                class="w-full mt-4"
                size="large"
                type="primary"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                登录
              </el-button>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
